package com.zhiyou.app.shop.common;

import java.io.File;
import java.util.Map;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import com.opensymphony.xwork2.ActionContext;
import com.google.gson.JsonObject;
import com.opensymphony.xwork2.ActionSupport;
import com.zhiyou.app.shop.common.util.Page;
import com.zhiyou.app.shop.common.util.ShopConstants;
import com.zhiyou.app.shop.manager.dao.pojo.UserDetail;

/**
 * @CreateTime: 2011-3-25 下午02:24:27
 * @author kewei
 * 
 */
@SuppressWarnings("serial")
public class BaseAction extends ActionSupport implements SessionAware{
	protected int pageNo=1;
	protected int pageSize = 30;
	private Page page;//分页对象
	protected String currentPath="";
	protected String errorMessage;
	protected Map<String, Object> session;

	public String getWebApplicationAbsolutePath() {
		String realPath = getServletContext().getRealPath("/");
		if ((realPath != null) && (!(realPath.endsWith("/")))) {
			return realPath + "/";
		}
		return realPath;
	}

	public static ServletContext getServletContext() {
		return ServletActionContext.getServletContext();
	}
	protected String getRealPath(String path){
		return getServletContext().getRealPath(path)+File.separator;
	}
	protected HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	protected HttpSession getHttpSession() {
		return ServletActionContext.getRequest().getSession();
	}

	protected HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	
	/**
	 * @return the pageNo
	 */
	public int getPageNo() {
		return pageNo;
	}
	
	protected Page getInitedPage(){
		Cookie[] cookies = this.getRequest().getCookies();
		String uri = this.getRequest().getRequestURI();
		if(cookies != null){
			for(Cookie cookie : cookies){
				if(uri.indexOf(cookie.getName())>0){
					try{
					  this.pageSize=Integer.parseInt(cookie.getValue());
					} catch (Exception e){
						
					}
					break;
				}
			}
		}
		page = new Page(this.pageNo , this.pageSize);
		return page;
	}
	
	protected Page getWebSitePage(){
		page = new Page(this.pageNo , this.pageSize);
		return page;
	}
	/**
	 * @param pageNo the pageNo to set
	 */
	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}

	/**
	 * @return the pageSize
	 */
	public int getPageSize() {
		return pageSize;
	}

	/**
	 * @param pageSize the pageSize to set
	 */
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	
	/**
	 * @return the page
	 */
	public Page getPage() {
		return page;
	}

	/**
	 * @param page the page to set
	 */
	public void setPage(Page page) {
		this.page = page;
	}

	/**
	 * @return the currentPath
	 */
	public String getCurrentPath() {
		return currentPath;
	}

	/**
	 * @param currentPath the currentPath to set
	 */
	public void setCurrentPath(String currentPath) {
		this.currentPath = currentPath;
	}

	/**
	 * @return the errorMessage
	 */
	public String getErrorMessage() {
		return errorMessage;
	}

	/**
	 * 打印异常信息并将异常信息格式化输出到前台
	 * @param e
	 */
	public void setErrorMessage(Exception e) {
		this.getLog().error(e.getMessage(), e);
		if(e instanceof AycshopException){
			AycshopException aye = (AycshopException)e;
			if(aye.getParams()!=null){
				this.errorMessage = getText(e.getMessage(),aye.getParams());
			}else{
				this.errorMessage = getText(e.getMessage());
			}
		}else{
			this.errorMessage = e.getMessage();
		}
	}
	
	/**
	 * 在没有异常发生的情况下，传递给页面的提示信息
	 * @param messageKey
	 */
	protected void setMessage(String messageKey){
		this.errorMessage = getText(messageKey);
	}
	
	/**
	 * @return the currentUser
	 */
	public UserDetail getCurrentUser() {
		UserDetail user = (UserDetail) getSession().get(ShopConstants.LOGIN_USER);
		return user;
		//to delete
//		return null;
	}
	
	private static final String passwordSalt="welcome to zhengzhou";
	private static final int passwordEncoderLength=256;
	private static final boolean passwordEncode=true;
	
/*	protected String encodePassword(String pass){
		if(passwordEncode) {
			ShaPasswordEncoder encoder=new ShaPasswordEncoder(passwordEncoderLength);
			return encoder.encodePassword(pass, passwordSalt);
		}else{
			return pass;
		}
		
	}
*/
	/**
	 * @return the basePath
	 */
	public String getBasePath() {
		return this.getRequest().getContextPath();
	}

	
	
	public void like(DetachedCriteria dc , String proName , String proValue , MatchMode mode){
		if(StringUtils.isNotBlank(proValue)){
			dc.add(Restrictions.like(proName, proValue, mode));
		}
	}
	
	public void eq(DetachedCriteria dc , String proName , String proValue){
		if(StringUtils.isNotBlank(proValue)){
			dc.add(Restrictions.eq(proName, proValue));
		}
	}
	
	protected Log getLog(){
		return LogFactory.getLog(this.getClass());
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	public Map<String, Object> getSession() {
		return ActionContext.getContext().getSession();
	}
	
	
	/**打印json格式字符串**/
	public static final String AJAX_RESULT = "result";
    public static final String AJAX_MESSAGE = "message";
	protected void printJSON(HttpServletResponse response ,InnerObject inner){
		JsonObject json = new JsonObject();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain");
		response.setHeader("Cache-Control","no-cache");
		response.setHeader("Pragma","no-cache");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			inner.execute(json);
			json.addProperty(AJAX_RESULT, Boolean.TRUE);
		} catch (Exception e) {
			this.setErrorMessage(e);
			json.addProperty(AJAX_RESULT, Boolean.FALSE);
			json.addProperty(AJAX_MESSAGE, this.getErrorMessage());
		}finally {
			if(null != out){
				out.print(json.toString());
				out.flush();
				out.close();
			}
		}
	}
	
	/**
	 * 判断当前用户是否具有所需的角色
	 * @param role
	 * @return
	 */
	public boolean hasRole(int role){
		UserDetail ud = this.getCurrentUser();
		if(null == ud) return false;
		return ud.getRole()<=role ? true:false;
	}
}
